<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.goods_specification_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          type="primary"
          size="small"
          @click.stop="handleShowSpecificationData(row)"
        >规格数据
        </el-button>
      </template>
    </avue-crud>
    <el-drawer
      title="商品规格数据"
      :visible.sync="specificationDataVisible"
      append-to-body
      :before-close="handleSpecificationDataClose"
      size="1000px"
    >
      <basic-container>
        <avue-crud
          :option="optionSpecificationData"
          :data="dataSpecificationData"
          :page="pageSpecificationData"
          :table-loading="specificationDataLoading"
          v-model="specificationDataForm"
          @row-update="specificationDataUpdate"
          @row-save="specificationDataSave"
          @row-del="specificationDataDel"
          :before-open="beforeOpenSpecificationData"
          ref="crudScope"
          @selection-change="selectionChangeSpecificationData"
        >
          <template slot-scope="{row}"
                    slot="goodsSpecificationId">
            <span>{{specificationName}}</span>
          </template>
        </avue-crud>
      </basic-container>
    </el-drawer>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/goods/goods_specification";
  import {getList as getDataList, getDetail as getDataDetail, add as addData, update as updateData, remove as removeData} from "@/api/goods/goods_specification_data";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        specificationDataVisible: false,
        specificationDataLoading: false,
        selectionListSpecificationData: [],
        pageSpecificationData: {
          pageSize: 100,
          currentPage: 1,
          total: 0,
        },
        specificationDataForm: {},
        specificationId: "",
        specificationName: "",
        specificationDataId: "",
        dataSpecificationData: [],
        optionSpecificationData: {
          tip: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          menuWidth: '300',
          menuType: 'button',
          viewBtn: false,
          menu: true,
          selection: true,
          dialogClickModal: false,
          prop: "商品规格数据",
          column: [
            {
              label: "规格类型",
              prop: "goodsSpecificationId",
              slot: true,
              addDisabled: true,
              editDisabled: true
            },
            {
              label: "数据名称",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入数据名称",
                trigger: "blur"
              }]
            },
            {
              label: "增减金额",
              prop: "increaseOrDecrease",
              type: "number"
            },
            {
              label: "排序",
              prop: "sort",
              value: 99,
              type: "number",
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            },
            {
              label: "图片地址",
              prop: "pictureUrl",
              dataType: 'string',
              type: 'upload',
              span: 24,
              listType: 'picture-img',
              propsHttp: {
                res: 'data',
                url: 'link',
                name: 'originalName'
              },
              canvasOption: {
                text: 'shianjun',
                ratio: 0.1
              },
              limit: 2,
              tip: '只能上传jpg/png文件，且不超过500kb',
              action: '/api/blade-resource/oss/endpoint/put-file'
            },
            {
              label: "描述",
              prop: "description",
              type: "textarea",
              hide: true
            }
          ],
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 100,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          tree: true,
          index: true,
          menuWidth: '300',
          menuType: 'button',
          viewBtn: false,
          selection: true,
          column: [
            {
              label: "规格名称",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入商品规格名称",
                trigger: "blur"
              }]
            },
            {
              label: "排序",
              prop: "sort",
              value: 99,
              type: "number",
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            },
            {
              label: "描述",
              prop: "description",
              type: "textarea"
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.goods_specification_add, false),
          viewBtn: this.vaildData(this.permission.goods_specification_view, false),
          delBtn: this.vaildData(this.permission.goods_specification_delete, false),
          editBtn: this.vaildData(this.permission.goods_specification_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      beforeOpenSpecificationData(done, type) {
        if (["edit", "view"].includes(type)) {
          this.specificationDataForm.goodsSpecificationId = this.specificationName;
          getDataDetail(this.specificationDataForm.id).then(res => {
            this.specificationDataForm = res.data.data;
            this.specificationDataForm.goodsSpecificationId = this.specificationName;
          });
        }
        this.optionSpecificationData.column.filter(item => {
          if (item.prop === "goodsSpecificationId") {
            item.value = this.specificationName;
          }
        });
        done();
      },
      specificationDataSave(row, done, loading) {
        row.goodsSpecificationId = this.specificationId;
        addData(row).then(() => {
          done();
          this.onLoadSpecificationData(this.pageSpecificationData);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      specificationDataUpdate(row, index, done, loading) {
        row.goodsSpecificationId = this.specificationId;
        updateData(row).then(() => {
          done();
          this.onLoadSpecificationData(this.pageSpecificationData);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      specificationDataDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeData(row.id);
          })
          .then(() => {
            this.onLoadSpecificationData(this.pageSpecificationData);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleShowSpecificationData(row) {
        this.specificationDataVisible = true;
        this.specificationId = row.id;
        this.specificationName = row.name;
        this.onLoadSpecificationData(this.pageSpecificationData);
      },
      handleSpecificationDataClose(hide) {
        hide();
      },
      onLoadSpecificationData(page, params = {}) {
        this.specificationDataLoading = true;
        const values = {
          ...params,
          goodsSpecificationId: this.specificationId,
        };
        getDataList(
          page.currentPage,
          page.pageSize,
          Object.assign(values, this.query)
        ).then((res) => {
          const data = res.data.data;
          this.pageSpecificationData.total = data.total;
          this.dataSpecificationData = data.records;
          this.selectionListSpecificationData = [];
          this.specificationDataLoading = false;
        });
      },
      selectionChangeSpecificationData(list) {
        this.selectionListSpecificationData = list;
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
